﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;
using EIIS.Infrastructure.Model.System.Authority;
using EIIS.Infrastructure.Repositories.System.Authority;

namespace EIIS.Infrastructure.Repositories.Implement
{
    public class RoleRepository : RepositoryBase<Role>, IRoleRepository
    {
        public IQueryable<Role> LoadAllWithPage(out long total, int page, int rows, string order, string sort)
        {
            var list = this.LoadAll();
            total = list.LongCount();
            if (!string.IsNullOrEmpty(order) && !string.IsNullOrEmpty(sort))
            {
                list = list.OrderBy(sort + " " + order);
            }
            list = list.Skip((page - 1) * rows).Take(rows);
            return list;
        }

        public IQueryable<Role> GetByIdWithMenuAndPermissions(string strId)
        {
            var query = Session.CreateQuery(@"select distinct t from Role as t
                                                    left join fetch t.MenuNodes
                                                    left join fetch t.ActionPermissions
                                                   where t.Id=:Id");
            query.SetString("Id", strId);

            return query.List<Role>().AsQueryable();
        }

        public void SaveRole(Role role, string inheritedRoleId)
        {
            if (string.IsNullOrEmpty(inheritedRoleId) == false)
            {
                var query = GetByIdWithMenuAndPermissions(inheritedRoleId);
                if (query != null && query.Count() > 0)
                {
                    Role inheritedRole = query.First();
                    role.MenuNodes = new Iesi.Collections.Generic.HashedSet<MenuNode>();
                    role.ActionPermissions = new Iesi.Collections.Generic.HashedSet<ActionPermission>();
                    role.MenuNodes.AddAll(inheritedRole.MenuNodes);
                    role.ActionPermissions.AddAll(inheritedRole.ActionPermissions);                    
                }
            }
            SaveOrUpdate(role);
        }
    }
}
